package mapper

import (
	"errors"
	"fmt"
	"im/global"
	"im/model"
	"im/model/request"

	"gorm.io/gorm"
)

type ChatGroupMapper struct{}

// 创建群
func AddGroup(cgr request.ChatGroupReq) (model.ChatGroup, error) {
	var chatGroup = &model.ChatGroup{
		OwnerId: cgr.OwnerId,
		Desc:    cgr.Desc,
		Icon:    cgr.Icon,
		Name:    cgr.Name,
	}
	return *chatGroup, global.DB.Create(chatGroup).Error
}

// 修改群信息
func UpdateGroup(cg model.ChatGroup) (model.ChatGroup, error) {
	return cg, global.DB.Model(&model.ChatGroup{}).Where("id = ?", cg.ID).Updates(&cg).Error
}

// 获取该用户所拥有的群列表
func ListGroups(cgr request.ChatGroupReq) (interface{}, error) {
	var chatGroups []model.ChatGroup

	d := global.DB.Model(&model.ChatGroup{})
	if name := cgr.Name; name != "" {
		// 字符串模糊查询
		d.Where("name like concat('%', ?, '%')", name)
	}
	return chatGroups, d.Where("owner_id = ? ", cgr.OwnerId).Find(&chatGroups).Error
}

// 删除群信息
func DelGroup(cgr request.ChatGroupReq) (model.ChatGroup, error) {
	var chatGroup model.ChatGroup
	d := global.DB.Model(&model.ChatGroup{})
	if id := cgr.ID; id != 0 {
		d.Where("id = ?", id)
	}
	if ownerId := cgr.OwnerId; ownerId != 0 {
		d.Where("owner_id = ?", ownerId)
	}
	if errors.Is((d.Find(&chatGroup).Error), gorm.ErrRecordNotFound) {
		return chatGroup, errors.New("删除失败, 该群不存在")
	}
	err := global.DB.Delete(&chatGroup).Error
	if err == nil {
		// 删除群下所有成员
		_, err = DelMember(request.ChatGroupMemberReq{
			GroupId: cgr.ID,
		})
		if err != nil {
			fmt.Println(err.Error())
			// global.LOG.Error(err.Error())
		}
	}
	return chatGroup, err
}
